// pages/addCourse/addCourse.ts
import { Course, AppSettings } from '@/typings';
import { showToast, generateUniqueId } from '../../../../../../utils/base';

const DEFAULT_SETTINGS: AppSettings = {
  totalWeeks: 0,
  startDate: '',
  lessonTimes: [],
};

Page({
  data: {
    isEditMode: false,
    courseId: '',
    formData: {
      id: '',
      weekday: new Date().getDay(),
      lessonIndex: 0,
      weekType: 'every' as 'every' | 'single' | 'double',
      courseName: '',
      teacher: '',
      room: '',
      status: 'enable' as 'enable' | 'disable',
      remark: '',
      color: 'blue' as 'orange' | 'blue' | 'green',
    },
    appSettings: DEFAULT_SETTINGS,
    weekdayColumns: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    lessonIndexColumns: [] as { text: string; value: number }[],
    weekTypeColumns: [
      { text: '每周', value: 'every' },
      { text: '单周', value: 'single' },
      { text: '双周', value: 'double' },
    ],
    weekTypeMap: { 'every': '每周', 'single': '单周', 'double': '双周' },
    showLessonIndexPicker: false,
    showWeekTypePicker: false,
    selectedLessonIndex: 0,
    selectedWeekType: 0,
  },

  onLoad(options: { id?: string }) {
    this.loadSettingsAndInitForm(options.id);
  },

  loadSettingsAndInitForm(courseId?: string) {
    try {
      const storedSettingsStr = wx.getStorageSync('appSettings');
      let appSettings: AppSettings = storedSettingsStr ? JSON.parse(storedSettingsStr) : DEFAULT_SETTINGS;
      appSettings.lessonTimes.sort((a, b) => a.index - b.index);

      const lessonIndexColumns = appSettings.lessonTimes.map(lt => ({
        text: `第${lt.index}节 (${lt.startTime}-${lt.endTime})`,
        value: lt.index,
      }));

      this.setData({
        appSettings,
        lessonIndexColumns,
      });

      if (courseId) {
        this.setData({
          isEditMode: true,
          courseId: courseId,
        });
        this.loadCourseDetails(courseId);
      } else {
        const defaultLessonIndex = lessonIndexColumns.length > 0 ? lessonIndexColumns[0].value : 0;
        const defaultLessonIndexColIndex = lessonIndexColumns.findIndex(col => col.value === defaultLessonIndex);
        this.setData({
          'formData.lessonIndex': defaultLessonIndex,
          selectedLessonIndex: defaultLessonIndexColIndex !== -1 ? defaultLessonIndexColIndex : 0,
        });
      }
    } catch (e) {
      console.error('加载设置失败', e);
      showToast('加载设置失败，请检查设置页面');
    }
  },

  loadCourseDetails(id: string) {
    wx.showLoading({ title: '加载中', mask: true });
    try {
      const storedCoursesStr = wx.getStorageSync('courseList');
      const courses: Course[] = storedCoursesStr ? JSON.parse(storedCoursesStr) : [];
      const courseToEdit = courses.find(course => course.id === id);

      if (courseToEdit) {
        const selectedLessonIndex = this.data.lessonIndexColumns.findIndex(col => col.value === courseToEdit.lessonIndex);
        const selectedWeekType = this.data.weekTypeColumns.findIndex(col => col.value === courseToEdit.weekType);
        this.setData({
          formData: courseToEdit,
          selectedLessonIndex: selectedLessonIndex !== -1 ? selectedLessonIndex : 0,
          selectedWeekType: selectedWeekType !== -1 ? selectedWeekType : 0,
        });
      } else {
        showToast('未找到课程信息');
        setTimeout(() => wx.navigateBack(), 1500);
      }
    } catch (e) {
      console.error('加载课程详情失败', e);
      showToast('加载失败，请重试');
      setTimeout(() => wx.navigateBack(), 1500);
    } finally {
      wx.hideLoading();
    }
  },

  onFieldChange(event: WechatMiniprogram.CustomEvent) {
    const { field } = event.currentTarget.dataset;
    this.setData({
      [`formData.${field}`]: event.detail,
    });
  },

  onStatusChange(event: WechatMiniprogram.CustomEvent) {
    this.setData({
      'formData.status': event.detail ? 'enable' : 'disable',
    });
  },

  onWeekdayChange(event: WechatMiniprogram.PickerChange) {
    this.setData({
      'formData.weekday': parseInt(event.detail.value as string),
    });
  },

  onShowPicker(event: WechatMiniprogram.CustomEvent) {
    const { pickerType } = event.currentTarget.dataset;
    if (pickerType === 'lessonIndex') {
      if (this.data.lessonIndexColumns.length === 0) {
        showToast('请先在“设置”中添加节次时间段！');
        return;
      }
      this.setData({ showLessonIndexPicker: true });
    } else if (pickerType === 'weekType') {
      this.setData({ showWeekTypePicker: true });
    }
  },

  onClosePicker() {
    this.setData({
      showLessonIndexPicker: false,
      showWeekTypePicker: false,
    });
  },

  onLessonIndexConfirm(event: WechatMiniprogram.CustomEvent) {
    const { value, index } = event.detail;
    this.setData({
      'formData.lessonIndex': value.value,
      selectedLessonIndex: index,
    });
    this.onClosePicker();
  },

  onWeekTypeConfirm(event: WechatMiniprogram.CustomEvent) {
    const { value, index } = event.detail;
    this.setData({
      'formData.weekType': value.value,
      selectedWeekType: index,
    });
    this.onClosePicker();
  },

  getRandomColor(): 'orange' | 'blue' | 'green' {
    const colors = ['orange', 'blue', 'green'];
    return colors[Math.floor(Math.random() * colors.length)];
  },

  async onSubmit() {
    const { formData, isEditMode, courseId } = this.data;

    if (!formData.courseName || formData.weekday === undefined || !formData.lessonIndex || !formData.weekType) {
      showToast('请填写所有必填项');
      return;
    }

    if (formData.lessonIndex === 0) {
      showToast('请选择有效的节次');
      return;
    }

    wx.showLoading({ title: isEditMode ? '更新中...' : '添加中...', mask: true });

    try {
      const storedCoursesStr = wx.getStorageSync('courseList');
      let allCourses: Course[] = storedCoursesStr ? JSON.parse(storedCoursesStr) : [];

      if (isEditMode) {
        const index = allCourses.findIndex(c => c.id === courseId);
        if (index !== -1) {
          allCourses[index] = { ...formData, id: courseId };
        } else {
          showToast('未找到要更新的课程');
          wx.hideLoading();
          return;
        }
      } else {
        const newCourse: Course = {
          ...formData,
          id: generateUniqueId(),
          color: this.getRandomColor(),
        };
        allCourses.push(newCourse);
      }

      wx.setStorageSync('courseList', JSON.stringify(allCourses));
      wx.hideLoading();
      showToast(isEditMode ? '课程更新成功！' : '课程添加成功！');

      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel) {
        eventChannel.emit('courseUpdated');
      }

      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    } catch (e) {
      console.error('保存课程失败', e);
      wx.hideLoading();
      showToast(isEditMode ? '课程更新失败' : '课程添加失败');
    }
  },
});
